package com.pl.flush;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


@Service
public class DbFlushScheduleService {
    private static List<DbFlushCacheUtil> flushCacheUtils = new ArrayList<>();

    private static ThreadFactory FLUSH_THREAD_FACTORY = ThreadFactoryBuilder.create().setNamePrefix("notify-").build();

    public static ThreadPoolExecutor FLUSH_EXECUTOR = new ThreadPoolExecutor(8, 16, 300L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(128), FLUSH_THREAD_FACTORY, new ThreadPoolExecutor.CallerRunsPolicy());


    public static void addDbFlushCache(DbFlushCacheUtil flushCacheUtil) {
        flushCacheUtils.add(flushCacheUtil);
    }


    @Async
    @Scheduled(fixedDelayString = "${cmp.mybatis.flush.fixedDelay:3000}")
    public void flushCache() {
        for (DbFlushCacheUtil flushCacheUtil : flushCacheUtils) {
            FLUSH_EXECUTOR.execute(flushCacheUtil::flushCache);
        }
    }
}


